//获取应用实例
var app = getApp();
Page({
  data: {
    regFlag: true,
    remind: '加载中',
    angle: 0,
    userInfo: {}
  },
  
  onLoad:function(){
    this.checkLogin(); //加载时候触发校验登录功能
  },

  onShow:function(){

  },

  onReady: function(){
    var that = this;
    setTimeout(function(){
      //已加载完毕
      that.setData({
        remind: ''
      });
    }, 1000);
    wx.onAccelerometerChange(function(res) {
      var angle = -(res.x*30).toFixed(1);
      if(angle>14){ angle=14; }
      else if(angle<-14){ angle=-14; }
      if(that.data.angle !== angle){
        that.setData({
          angle: angle
        });
      }
    });
  },

  checkLogin: function () {
    var that = this;
    wx.login({
      //获取的res为用户登录凭证（有效期五分钟）,用于换取openid等信息
      success: function (res) {
        if (!res.code) {
          app.alert({
            'content': '登录失败，请重试'
          });
          return;
        }
        //服务端check-reg
        wx.request({
          url: app.buildUrl('/user/check-reg'),
          header: app.getRequestHeader(),
          method: 'POST',
          data: {
            code: res.code
          },
          success: function (res) {
            if (res.data.code != 200) {
              that.setData({
                regFlag: false
              });
              return;
            }
            app.setCache("token", res.data.data.token);
            that.setUserID(parseInt(res.data.data.token.split("#")[1]));
          }
        });
      }
    });
  },

  loginCYC(e) {
    var that = this;
    wx.getUserProfile({
      desc: '用于完善资料', 
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        });
        var data = this.data.userInfo;
        wx.login({
          success: function (res) {
            if (!res.code) {
              app.alert({
                'content': '无法获取code,登录失败,请重试'
              });
              return;
            }
            data['code'] = res.code; //用于获取openID

            wx.request({ //将用户信息和code传给后端
              url: app.buildUrl('/user/login'),
              header: app.getRequestHeader(), //添加头部content-type和Authorization
              method: "POST",
              data: data,
              success: function (res) {
                if (res.data.code != 200) {
                  app.alert({
                    'content': res.data.msg
                  });
                  return;
                }
                app.setCache("token", res.data.data.token);
                that.setUserID(parseInt(res.data.data.token.split("#")[1]));
                that.goToIndex();
              }
            })
          }
        });
      }
    });
  },

  goToIndex:function(){
    wx.switchTab({
      url: '/pages/message/message',
    });
  },

  setUserID:function(uid){
    app.globalData.userID = uid;
  }
});